import 'package:flutter/material.dart';
import 'package:flutter_house_manager/pages/House/house_detail.dart';
import 'package:flutter_house_manager/pages/House/house_list.dart';
import 'package:flutter_house_manager/pages/Location/build_list.dart';
import 'package:flutter_house_manager/pages/Location/house_form.dart';
import 'package:flutter_house_manager/pages/Location/location_list.dart';
import 'package:flutter_house_manager/pages/Location/room_list.dart';
import 'package:flutter_house_manager/pages/Login/index.dart';
import 'package:flutter_house_manager/pages/NotFound/not_found.dart';
import 'package:flutter_house_manager/pages/NoticeDetail/index.dart';
import 'package:flutter_house_manager/pages/Profile/index.dart';
import 'package:flutter_house_manager/pages/TabsPage/index.dart';
import 'package:flutter_house_manager/utils/TokenManager.dart';

void main() {
  runApp(MaterialApp(
    title: '房屋管理系统',
    initialRoute: '/',
    routes: {
      '/': (context) => const TabsPage(),
      '/noticeDetail': (context) => const NoticeDetail(),
      '/login': (context) => const LoginPage(),
      // '/profile': (context) => const ProfilePage(),
    },
    // onGenerateRoute中不能有异步代码，必须是同步的
    // 因此需要将tokenManager中的getToken方法修改成同步操作
    onGenerateRoute: (setting) {
      // 1.获取token
      String token = tokenManager.getToken();
      // 2.没有token，跳转至登录界面
      if (token.isEmpty) {
        return MaterialPageRoute(
          builder: (context) => LoginPage(
            toName: setting.name,
          ),
        );
      }
      // 3.有token，跳转至目标页面
      if (setting.name == '/profile') {
        return MaterialPageRoute(builder: (context) => const ProfilePage());
      }
      // 房屋列表
      if (setting.name == '/house_list') {
        return MaterialPageRoute(builder: (context) => const HouseList());
      }
      // 定位列表
      if (setting.name == '/location_list') {
        return MaterialPageRoute(builder: (context) => const LocationList());
      }
      // 楼栋列表
      if (setting.name == '/building_list') {
        return MaterialPageRoute(builder: (context) => const BuildingList());
      }
      // 房间号列表
      if (setting.name == '/room_list') {
        return MaterialPageRoute(builder: (context) => const RoomList());
      }
      // 小区房间
      if (setting.name == '/house_form') {
        String id = '';
        if (setting.arguments != null) {
          id = (setting.arguments as Map)['id'];
        }
        return MaterialPageRoute(
          builder: (context) => HouseForm(id: id),
        );
      }
      // 房屋详情
      if (setting.name == '/house_detail') {
        return MaterialPageRoute(
          // 传递路由对象
          settings: setting,
          builder: (context) => const HouseDetail(),
        );
      }
      //  4. 没有匹配到任何页面, 去404页面
      return MaterialPageRoute(
        builder: (context) => const NotFound(),
      );
    },
  ));
}
